<template>
    <table style="width: 1200px;">
        <tr>
            <td rowspan="6">
                <img :src="files + form.traceabilityPicture" width="250" height="200"
                    style="border-radius: 10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <el-button style="float: right;" @click="updateDate()">修改基础信息</el-button>

                <el-button style="float: right;" @click="Visible = true">导出溯源码</el-button>
            </td>
            <td></td>
        </tr>
        <tr>
            <td colspan="2"><span style="font-size: 50px;">{{ form.commodityName }}</span> </td>

        </tr>
        <tr>

            <td>生产批次：{{ form.productionLot }}</td>
            <td style="padding-left: 20px;">保质期：{{ form.shelfLife }}天</td>
        </tr>
        <tr>
            <td>生产许可证号：{{ form.manufacturingLicense }}</td>
            <td style="padding-left: 20px;">生产企业：{{ form.enterpriseName }}</td>
        </tr>
        <tr>
            <td colspan="2">产品检验报告:
                <el-upload :on-success="Cjimg" v-model:file-list="imagesList" limit="9" multiple
                    action="http://localhost:44228/api/Goods/UploadFile" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </td>
        </tr>
    </table>
    <table style="margin-top: 40px;width: 100%;">
        <el-tabs type="card" class="demo-tabs">
            <el-tab-pane label="养殖信息" name="first">
                <CulList></CulList>
            </el-tab-pane>
            <el-tab-pane label="屠宰信息" name="second">
                <SlaList></SlaList>
            </el-tab-pane>
            <el-tab-pane label="深加工信息" name="third">
                <ProList></ProList>
            </el-tab-pane>
        </el-tabs>
    </table>

    <!-- 修改基础信息 -->
    <div>
        <el-drawer v-model="drawer2" title="溯源修改" size="30%">
            <div>
                <!-- form表单 -->
                <el-form ref="ruleFormRef" style="max-width: 600px" :model="form1" :rules="rules" label-width="auto"
                    class="demo-ruleForm" :size="formSize" status-icon>
                    <el-form-item label="商品名称" prop="commodityId">
                        <el-select v-model="form1.commodityId" placeholder="请选择商品">
                            <el-option v-for="item in goodslist" :key="item.id" :label="item.commodityName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生产批次" prop="productionLot">
                        <el-input v-model="form1.productionLot" />
                    </el-form-item>
                    <el-form-item label="保质期（天）" prop="shelfLife">
                        <el-input v-model="form1.shelfLife" />
                    </el-form-item>
                    <el-form-item label="生产许可证号" prop="manufacturingLicense">
                        <el-input v-model="form1.manufacturingLicense" />
                    </el-form-item>
                    <el-form-item label="生产企业" prop="enterpriseName">
                        <el-input v-model="form1.enterpriseName" />
                    </el-form-item>
                    <el-form-item label="封面图" prop="traceabilityPicture">
                        <el-upload class="avatar-uploader" action="http://localhost:44228/api/Goods/UploadFile"
                            :show-file-list="false" :on-success="handleAvatarSuccess1">
                            <img v-if="form1.traceabilityPicture" :src="files + form1.traceabilityPicture"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm1(ruleFormRef)">
                            保存
                        </el-button>
                        <el-button @click="resetForm1(ruleFormRef)">重置</el-button>
                        <el-button @click="drawer2 = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
    </div>
    <div>
        <!-- 导出源码 -->
        <el-dialog v-model="Visible" title="导出设置" width="500" :before-close="handleClose">
            <template #footer>
                <div>
                    <input v-model="text" placeholder="输入文本生成二维码地址" />
                    <button @click="generateQRCodeURL">生成二维码地址</button>
                    <button v-if="qrCodeURL" @click="downloadTXT">下载文本文件</button>
                    <div v-if="qrCodeURL">
                        <p>二维码地址：<a :href="qrCodeURL" target="_blank">点击查看二维码</a></p>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import type { UploadProps, UploadUserFile } from 'element-plus'
import CulList from '../views/Bread.vue';
import SlaList from '../views/Slaughter.vue';
import ProList from '../views/DeepProcessing.vue';
//溯源码
import QRCode from 'qrcode'
const Visible = ref(false)
//溯源码
//生成二维码
const text = ref('');
const qrCodeURL = ref('');
const generateQRCodeURL = () => {
    QRCode.toDataURL(text.value)
        .then((url) => {
            qrCodeURL.value = url;
        })
        .catch((err) => {
            console.error(err);
        });
};
// 导出文本文件
const downloadTXT = () => {
    const blob = new Blob([qrCodeURL.value], { type: 'text/plain;charset=utf-8' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'qrcode-url.txt'; // 你可以修改文件名
    link.click();
};

//form表单
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//抽屉

import type { DrawerProps } from 'element-plus'
const drawer2 = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const form1 = reactive({
    id: 0,
    commodityId: '',
    productionLot: "",
    shelfLife: 0,
    manufacturingLicense: "",
    enterpriseName: "",
    traceabilityPicture: "",
    inspection: "",
    createBy: "string",
    createDate: null,
    isDel: false,
})
//反填
const updateDate = () => {
    drawer2.value = true
    getGoodslist();
    axios.get("Goods/FindPro?id=" + route.query.id)
        .then(res => {
            form1.commodityId = res.data.data.commodityId;
            form1.productionLot = res.data.data.productionLot;
            form1.shelfLife = res.data.data.shelfLife;
            form1.manufacturingLicense = res.data.data.manufacturingLicense;
            form1.enterpriseName = res.data.data.enterpriseName;
            form1.traceabilityPicture = res.data.data.traceabilityPicture;
            form1.inspection = res.data.data.inspection;
            form1.id = res.data.data.id;
            form1.createBy = res.data.data.createBy;
            form1.createDate = res.data.data.createDate;
            form1.isDel = res.data.data.isDel;
        })
        .catch(error => {
            console.log(error)
        })
}
//修改
const submitForm1 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post("Goods/UpdatePro", form1).then(response => {
                console.log(response.data)
                if (response.data.code == 1) {
                    ElMessage({
                        message: response.data.msg,
                        type: 'success',
                    })
                    form1.value = ''
                    drawer2.value = false
                    location.reload()
                } else {
                    ElMessage.error(response.data.msg)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm1 = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
//下拉框
const goodslist = ref([]);
const getGoodslist = () => {
    axios.get("Goods/GetCommodity").then(response => {
        goodslist.value = response.data.data;
    })
}
//修改溯源基础信息图片
const pictures = ref("")
const handleAvatarSuccess1 = (file: any) => {
    form1.traceabilityPicture = file.data
    pictures.value = "http://localhost:44228/Image/" + form1.traceabilityPicture
    console.log(form1.traceabilityPicture)
}
//上传图片变量
const files = "http://localhost:44228/Image/"

const route = useRoute();
const router = useRouter();


const form = reactive({
    id: 0,
    commodityId: '',
    productionLot: "",
    shelfLife: 0,
    manufacturingLicense: "",
    enterpriseName: "",
    traceabilityPicture: "",
    inspection: "",
    createBy: "string",
    createDate: null,
    isDel: false,
    commodityName: "",

});
//反填
const Rdist = () => {
    axios.get("Goods/FindProOutput?id=" + route.query.id)
        .then(res => {
            form.commodityId = res.data.data.commodityId;
            form.productionLot = res.data.data.productionLot;
            form.shelfLife = res.data.data.shelfLife;
            form.manufacturingLicense = res.data.data.manufacturingLicense;
            form.enterpriseName = res.data.data.enterpriseName;
            form.traceabilityPicture = res.data.data.traceabilityPicture;
            form.inspection = res.data.data.inspection;
            form.id = res.data.data.id;
            form.createBy = res.data.data.createBy;
            form.createDate = res.data.data.createDate;
            form.isDel = res.data.data.isDel;
            form.commodityName = res.data.data.commodityName;
        })
        .catch(error => {
            console.log(error)
        })
}
//上传
const picture = ref("")

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imagesList = ref([])
const Getimages = () => {
    axios.get("Goods/GetImage?traceType=" + route.query.id)
        .then(res => {
            imagesList.value = res.data.data;
            imagesList.value.forEach(item => {
                item.url = files + item.value;
                console.log(item.value)
            })
        })
        .catch(error => {
            console.log(error)
        })
}
const handleRemove = (uploadFile: any) => {
    var id = uploadFile.name
    axios.get("Goods/DelImages?id=" + id)
        .then(res => {
        })
}

const handlePictureCardPreview = (uploadFile: any) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
//添加
const Cjimg = (value: any) => {
    var AddCjImages = reactive({
        traceType: route.query.id,
        urlImg: value.data,
        imageType: 0
    })
    axios.post("Goods/AddImages", AddCjImages)
        .then(res => {
            if (res.data.code == 1) {
                ElMessage({
                    message: res.data.msg,
                    type: 'success',
                })
                Getimages();
            }
            else {
                ElMessage.error(res.data.msg)
            }
        })
        .catch(error => {
            console.log(error)
        })
}

//钩子函数
onMounted(() => {
    Rdist();
    //反填检验照片
    Getimages();
})
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 150px;
    height: 150px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}
</style>